package com.can.Thread;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//线程创建方式三：实现Callable(拷A伯)

//总结:callable的好处
//1.可以定义返回值
//2.可以抛出异常
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestThread06Callable implements Callable<Boolean> {
    private String url; //网络图片地址
    private String fileName;    //保存的文件名

    //下载图片线程的执行体
    @Override
    public Boolean call() throws Exception {
        WebDownloaderCallable webDownloader = new WebDownloaderCallable();
        webDownloader.downloader(url,fileName);
        System.out.println("下载了文件名为==>:"+fileName);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        String url = "http://img.crawler.qq.com/lolwebschool/0/JAutoCMS_LOLWeb_38b05cbbe6239800e43e53ec85086958/0";
        String fileName = "TestThread06Callable实现多线程同步下载图片";
        String fileSuffix = ".jpg";
        TestThread06Callable t1 = new TestThread06Callable(url,fileName+"0"+fileSuffix);
        TestThread06Callable t2 = new TestThread06Callable(url,fileName+"1"+fileSuffix);
        TestThread06Callable t3 = new TestThread06Callable(url,fileName+"2"+fileSuffix);

        //创建执行服务：
        ExecutorService ser  = Executors.newFixedThreadPool(3); //线程池数量
        //执行提交：
        Future<Boolean> r1= ser.submit(t1);
        Future<Boolean> r2= ser.submit(t2);
        Future<Boolean> r3= ser.submit(t3);
        //获取结果：
        boolean rs1  = r1.get();
        boolean rs2  = r2.get();
        boolean rs3  = r3.get();
        //关闭服务：
        ser.shutdownNow();
    }
}

//下载器
class WebDownloaderCallable{
    //下载方法
    public void downloader(String url,String fileName){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(fileName));//拷贝一个URL变成一个文件
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常,downloader()方法出现问题");
        }
    }
}
